package ltd.nullpointer.tcp.core.util;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.UnsupportedEncodingException;

/**
 * 
 * @ClassName: Base64Util
 * @Description: base 64加密
 * @author zhangweilin
 * @date 2017年12月22日 下午3:53:31
 *
 */
public class Base64Util {
	// 加密
	public static String getBase64(String str) {
		byte[] b = null;
		String s = null;
		try {
			b = str.getBytes("utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		if (b != null) {
			s = new BASE64Encoder().encode(b);
		}
		return s;
	}

	// 解密
	public static String getFromBase64(String s) {
		byte[] b = null;
		String result = null;
		if (s != null) {
			BASE64Decoder decoder = new BASE64Decoder();
			try {
				b = decoder.decodeBuffer(s);
				result = new String(b, "utf-8");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	public static void main(String[] args) throws Exception {
		String str = "1234657964";
		String str2 = Base64Util.getBase64(str);
		System.out.println("str2: " + str2);
		String str3 = Base64Util.getFromBase64(str2);
		System.out.println("str3: " + str3);
	}
}